//************************************************************************
//Developed by Guo Ming Li 2009/2010
//Source code:
//  The source code may be freely modified or used but this credit section may not be removed 
//  The original author must be notified of any modifications plus a copy of 
//  the changed source code
//Contact info: mailto://gming.li@gmail.com
//************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace GML.BizTalk.OperationManager.Library
{
    public class HostInstances
    {
        //Function to Enumerate all HostInstances of "InProcess" type and start them
        public static bool EnumerateAndStart()
        {
            //Create EnumerationOptions and run wql query
            EnumerationOptions enumOptions = new EnumerationOptions();
            ManagementObjectSearcher searchObject = null;
            try
            {
                enumOptions.ReturnImmediately = false;
                //Search for all HostInstances of 'InProcess' type in the Biztalk namespace scope
                searchObject = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer", "Select * from MSBTS_HostInstance where HostType=1", enumOptions);

                //Enumerate through the result set and start each HostInstance if it is already stopped
                foreach (ManagementObject inst in searchObject.Get())
                {
                    //Check if ServiceState is 'Stopped'
                    if (inst["ServiceState"].ToString() == "1")
                    {
                        inst.InvokeMethod("Start", null);
                    }
                    System.Diagnostics.Debug.WriteLine("HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " was started successfully");
                }

                System.Diagnostics.Debug.WriteLine("All HostInstances started");
                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Failure while starting HostInstances - " + e.Message);
                Logger.doLog(Guid.NewGuid().ToString(), "Failure while starting HostInstances - " + e.Message, Logger.ServerityLevel.ERROR);
                Logger.doLog(Guid.NewGuid().ToString(), e.StackTrace, Logger.ServerityLevel.ERROR);
                return false;
            }
            finally
            {
                enumOptions = null;
                searchObject = null;
            }
        }
        public static bool StartAllHostInstances(out Exception ex)
        {
            //Create EnumerationOptions and run wql query
            EnumerationOptions enumOptions = new EnumerationOptions();
            ManagementObjectSearcher searchObject = null;
            try
            {
                enumOptions.ReturnImmediately = false;
                //Search for all HostInstances of 'InProcess' type in the Biztalk namespace scope
                searchObject = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer", "Select * from MSBTS_HostInstance where HostType=1", enumOptions);

                //Enumerate through the result set and start each HostInstance if it is already stopped
                foreach (ManagementObject inst in searchObject.Get())
                {
                    //Check if ServiceState is 'Stopped'
                    if (inst["ServiceState"].ToString() == "1")
                    {
                        inst.InvokeMethod("Start", null);
                    }
                    System.Diagnostics.Debug.WriteLine("HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " was started successfully");
                }

                System.Diagnostics.Debug.WriteLine("All HostInstances started");
                ex = null;
                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Failure while starting HostInstances - " + e.Message);
                Logger.doLog(Guid.NewGuid().ToString(), "Failure while starting HostInstances - " + e.Message, Logger.ServerityLevel.ERROR);
                Logger.doLog(Guid.NewGuid().ToString(), e.StackTrace, Logger.ServerityLevel.ERROR);
                ex = e;
                return false;
            }
            finally
            {
                enumOptions = null;
                searchObject = null;
            }
        }

        //Function to Enumerate all HostInstances of "InProcess" type and stop them
        public static bool EnumerateAndStop()
        {
            int iFailedCount = 0;
            //Create EnumerationOptions and run wql query
            EnumerationOptions enumOptions = new EnumerationOptions();
            ManagementObjectSearcher searchObject = null;
            try
            {
                enumOptions.ReturnImmediately = false;
                //Search for all HostInstances of 'InProcess' type in the Biztalk namespace scope
                searchObject = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer", "Select * from MSBTS_HostInstance where HostType=1", enumOptions);

                //Enumerate through the result set and start each HostInstance if it is already stopped
                foreach (ManagementObject inst in searchObject.Get())
                {
                    inst.InvokeMethod("Stop", null);
                    //Check if ServiceState is 'Stopped'
                    if (inst["ServiceState"].ToString() == "1")
                    {
                        System.Diagnostics.Debug.WriteLine("HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " was stopped successfully");
                        Logger.doLog(Guid.NewGuid().ToString(), "HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " was stopped successfully", Logger.ServerityLevel.INFO);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " failed to stop");
                        Logger.doLog(Guid.NewGuid().ToString(), "HostInstance of Host: " + inst["HostName"] + " and Server: " + inst["RunningServer"] + " failed to stop", Logger.ServerityLevel.INFO);
                        iFailedCount++;
                    }
                }

                System.Diagnostics.Debug.WriteLine("All HostInstances stopped");
                Logger.doLog(Guid.NewGuid().ToString(), "All HostInstances stopped", Logger.ServerityLevel.INFO);
                if (iFailedCount == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Failure while stopping HostInstances - " + e.Message);
                Logger.doLog(Guid.NewGuid().ToString(), "Failure while stopping HostInstances - " + e.Message, Logger.ServerityLevel.ERROR);
                Logger.doLog(Guid.NewGuid().ToString(), e.StackTrace, Logger.ServerityLevel.ERROR);
                return false;
            }
            finally
            {
                enumOptions = null;
                searchObject = null;
            }

        }

        public static bool RestartAllHostInstances()
        {
            return EnumerateAndStop() && EnumerateAndStart();
        }

    }
}
